﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth.Sts;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Common.DataAnnotations;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Aliyun
{
    /// <summary>
    /// 阿里云STS授权
    /// </summary>
    public class STSAuthorization
    {
        private readonly IConfiguration configuration;
        /// <summary>
        /// 阿里云STS授权
        /// </summary>
        /// <param name="configuration"></param>
        public STSAuthorization(IConfiguration configuration)
        {
            this.configuration = configuration;
        }
        /// <summary>
        /// 阿里云STS授权
        /// </summary>
        /// <param name="sessionName">会话名称</param>
        /// <param name="policy">授权策略</param>
        /// <returns></returns>
        public FuncResult<STSCredential> STSGrant(string sessionName, STSPolicy policy)
        {
            string accessKeyId = configuration[Constants.NAME_OF_ACCESS_ID];
            string accessKeySceret = configuration[Constants.NAME_OF_ACCESS_SECRET];
            //构建一个阿里云客户端，用于发起请求。
            //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySceret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            //构建请求，设置参数。关于参数含义和设置方法，请参见API参考。
            var request = new AssumeRoleRequest();
            request.RoleArn = "acs:ram::1308051966691219:role/oss-access";
            request.RoleSessionName = sessionName;
            if (policy != null)
            {
                request.Policy = Utils.ToJson(policy);
            }
            //发起请求，并得到响应。
            try
            {
                var response = client.GetAcsResponse(request);
                return FuncResult.Success(new STSCredential
                {
                    AccessKeyId = response.Credentials.AccessKeyId,
                    AccessKeySecret = response.Credentials.AccessKeySecret,
                    SecurityToken = response.Credentials.SecurityToken,
                    Expiration = response.Credentials.Expiration
                });
            }
            catch (ServerException e)
            {
                return FuncResult.Fail<STSCredential>(e.ErrorMessage ?? e.Message);
            }
            catch (ClientException e)
            {
                return FuncResult.Fail<STSCredential>(e.ErrorMessage ?? e.Message);
            }
        }
    }
}
